import { createRouter, createWebHashHistory } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useStore } from '@/pinia/index'
const routes = []
const router = createRouter({
  history: createWebHashHistory(), //哈希模式
  routes
})

const pinia = useStore()
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 1000
})
//请求拦截
service.interceptors.request.use(
  (config) => {
    config.headers.Authorization = pinia.jwt
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
//响应拦截
service.interceptors.response.use(
  (response) => {
    //  // 返回的status 以 2 开头会走这个
    return response.data
  },
  (error) => {
    // console.log(error)
    // // 响应拦截, status !== 200 会被这里拦截
    // if (error.response.status == 401) {
    //   ElMessage.error('token过期')
    //   router.push({ path: '/' })
    //   setTimeout(() => {
    //     window.location.reload()
    //   }, 2000)
    // }else{
    //   ElMessage.error('网络错误')
    // }
    // return Promise.reject(error)
    if(error && error.response){
    // 根据响应码具体处理
    switch (error.response.status) {
      case 401:
        ElMessage.error('未授权，请重新登录')
        router.push({ path: '/' })
        setTimeout(() => {window.location.reload()}, 2000)
        break;
      case 403:
        ElMessage.error('拒绝访问')
        break;
      default:
         ElMessage.error(`连接错误${error.response.status}`)
    }
    }else{
      ElMessage.error('网络错误')
      return Promise.reject(error)
    }
  }
)

export default service
